package com.course.service;

import com.course.dao.CourseOrderDao;
import com.course.model.CourseOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class CourseOrderService {
    @Autowired
    CourseOrderDao courseOrderDao;
    @Autowired
    CourseVieDataService courseVieDataService;
    @Autowired
    RedisService redisService;

    public CourseOrder findByUserCourse(Integer userId, Integer c_id) {
        return (CourseOrder) redisService.getVal("VIE_COURSE:ORDER_"+userId+"_"+c_id);
    }

    @Transactional
    public void addOrUpdate(CourseOrder co) {
        // 检查数据库是否有订单
        CourseOrder co_1 = courseOrderDao.findByUserCourse(co.getUserId(),co.getCourseId());
        if(co_1 == null){
            // 获取目前的剩余数量
            Integer apply_num = courseVieDataService.getApplyNumByCourseId(co.getCourseId());
            if(apply_num > 0){
            // 减库存
                courseVieDataService.reduceApplyNum(co.getCourseId(),apply_num);
                // 存放订单
                courseOrderDao.save(co);
                // redis保存
                redisService.setVal("VIE_COURSE:ORDER_"+co.getUserId()+"_"+co.getCourseId(),co);
            }
        }
    }
}
